package com.tledu.dangjian.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.tledu.dangjian.core.exception.UsernameRepeatException;
import com.tledu.dangjian.dao.IRoleDao;
import com.tledu.dangjian.model.Resource;
import com.tledu.dangjian.model.Role;
import com.tledu.dangjian.model.User;
import com.tledu.dangjian.service.IRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl extends BaseServiceImpl<Role, IRoleDao> implements IRoleService {
    public RoleServiceImpl(IRoleDao baseDao) {
        super(baseDao);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.SERIALIZABLE)
    public Integer insert(Role entity) {
        // 建立关联关系
        List<Integer> resourceIdList = new ArrayList<>();
        for (Resource resource : entity.getResourceList()) {
            resourceIdList.add(resource.getResourceId());
        }
        // 获取当前插入用户的id
        Integer num = baseDao.insert(entity);
        baseDao.addResource(resourceIdList, entity.getRoleId());
        return num;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(Role entity) {
        // 建立关联关系
        List<Integer> resourceIdList = new ArrayList<>();
        for (Resource resource : entity.getResourceList()) {
            resourceIdList.add(resource.getResourceId());
        }
        // 获取当前插入用户的id
        int num = baseDao.update(entity);
        baseDao.clearResource(entity.getRoleId());
        baseDao.addResource(resourceIdList, entity.getRoleId());
        return num;
    }
}
